/**
 * Created by Eoly on 2017/2/16.
 * Call http://palerock.cn
 */
var indexPage = angular.module('indexPage', ['ngRoute']);

/**
 * 过滤器
 */
indexPage.filter('append', function () {
    return function (value, text) {
        return app.appendText(value, text);
    }
});

indexPage.filter('explainPower', function () {
    return function (power) {
        return app.explainPower(power)
    }
});

/**
 * 主页
 */
indexPage.controller('index', function ($scope, $http) {
    $scope.suiMobileInit = function (isNotChangeContent) {
        // alert(isNotChangeContent);
        app.suiInit(isNotChangeContent);
    };


    // 轮播图信息
    $scope.sliderSrcList = [];
    var sliderCount = 3; // 指定轮播图数量

    // 所有团信息
    $scope.allGroup = [];

    //跳转团详情页面
    $scope.turnDetail = function (group) {
        sessionStorage.setItem('ptsc_detail_groupId', group.groupId);
        app.turnHref('index.html', '#index', 'group-detail.html');
    };

    //活动详情页面
    $scope.activeDetails = function (active) {
        sessionStorage.setItem('ptsc_detail_activeId', active.activityId);
        app.turnHref('index.html', '#index', 'active-detail.html');
        //$scope.activeId = sessionStorage.getItem('ptsc_detail_activeId');
        //console.log($scope.activeId);
    };

    var neededInfo = {line: 0, next: 7};

    // 获取主页团信息
    $scope.getTheIndexGroup = function () {

        $.showPreloader('请稍候');
        $http({
            method: 'get',
            url: net + '/group/find-groups',
            params: neededInfo
        }).then(function (res) {
            console.log(res);
            $.hidePreloader();
            if (!res.data.error) {
                $scope.allGroup = [];
                $scope.sliderSrcList = [];
                var groupList = res.data.dataList;
                for (var i = 0; i < groupList.length; i++) {
                    var singleImgs = [];
                    singleImgs = groupList[i];
                    singleImgs.src = eval(groupList[i].groupImgs);

                    for (var o = 0; o < singleImgs.src.length; o++) {
                        //遍历图片地址并加上服务器的url
                        singleImgs.src[o] = net + '/resources/img/' + singleImgs.src[o];
                    }
                    if (i < sliderCount) {
                        $scope.sliderSrcList.push(singleImgs);
                    } else {
                        $scope.allGroup.push(singleImgs);
                    }

                    setTimeout(function () {
                        $(function () {
                            $.initSwiper($('.content'));
                        });
                    }, 500);
                }
            } else {
                $.alert("错误代码:" + res.data.error + "," + res.data.mes)
            }
        }, function () {
            $.hidePreloader();
            $.alert('网络或设置错误');
        });
    };

    $scope.getNextGroupInfo = function () {
        neededInfo.line = neededInfo.line + neededInfo.next;
        $http({
            method: 'get',
            url: net + '/group/find-groups',
            params: neededInfo
        }).then(function (res) {
            console.log(res);
            if (!res.data.error) {
                var groupList = res.data.dataList;
                for (var i = 0; i < groupList.length; i++) {
                    var singleImgs = [];
                    singleImgs = groupList[i];
                    singleImgs.src = eval(groupList[i].groupImgs);

                    for (var o = 0; o < singleImgs.src.length; o++) {
                        //遍历图片地址并加上服务器的url
                        singleImgs.src[o] = net + '/resources/img/' + singleImgs.src[o];
                    }
                    $scope.allGroup.push(singleImgs);
                }
                if (groupList.length < neededInfo.next) {
                    // 加载完毕，则注销无限加载事件，以防不必要的加载
                    $.detachInfiniteScroll($('.infinite-scroll'));
                    // 删除加载提示符
                    $('.infinite-scroll-preloader').hide();
                }
                loading = false;
            } else {
                $.alert("错误代码:" + res.data.error + "," + res.data.mes);
                // 加载完毕，则注销无限加载事件，以防不必要的加载
                $.detachInfiniteScroll($('.infinite-scroll'));
                // 删除加载提示符
                $('.infinite-scroll-preloader').hide();
                loading = false;
            }
        }, function () {
            $.alert('网络或设置错误');
        });
    };

    $scope.saveToSearch = function (groupId, name) {
        var typeChecked = {};
        typeChecked.goodsTypeId = groupId;
        typeChecked.goodsTypeName = name;
        if (name !== null) {
            sessionStorage.setItem('ptsc_search_type_checked', JSON.stringify(typeChecked));
        } else {
            sessionStorage.removeItem('ptsc_search_type_checked')
        }
        if ($scope.keyWords != null) {
            sessionStorage.setItem('ptsc_search_key_words', $scope.keyWords);
        }
        app.turnHref('index.html', '#index', '#search');
    };

    /**
     * 图标的排列
     * */

    $scope.type_height = function () {
        var width = window.innerWidth;
        $('#my-type-content>ul>li').height(width * 0.10);
        $('#my-type-content>ul>li').width(width * 0.10);
        $('#my-type-content>ul>li').css("margin-left", width * 0.05);
        $('#my-type-content>ul>li').css("margin-Right", width * 0.05);


    };


});

/**
 * 我的
 */
indexPage.controller('mine', function ($scope, $http) {
    //声明用户信息
    $scope.userInfo = {};
    $scope.userInfos = {};
    //获取用户信息
    $scope.showUserInfo = function () {
        //获取登录信息
        var token = app.getUserToken();

        if (!token) {
            return;
        }

        //操作等待禁用用户操作
        $.showPreloader('请稍候');
        //从服务器获取用户信息
        $http({
            method: 'get',
            url: net + '/user/show-user-info',
            headers: {'Authorization': 'Bearer ' + token}
        }).then(
            //响应成功
            function (res) {
                if (!res.data.error) {

                    console.log(res.data);

                    //将获取的用户信息绑定给userInfo
                    $scope.userInfo = res.data.data;
                    console.log($scope.userInfo);
                    //因为userAvatar是只有图片文件名
                    //所以需要在前面加上服务器储存图片的地址，并自定义一个userAvatarAddress来储存
                    //地址：服务器路径+"/resources/img/"
                    $scope.userInfo.userAvatarAddress = net + "/resources/img/" + res.data.data.userAvatar;

                    //从服务器获得的性别数据不可以直接展示所以自定一个userSexWord来储存性别
                    //0:男，1:女
                    $scope.userInfo.userSexWord = $scope.userInfo.userSex == 0 ? "男" : "女";

                    //启用用户操作
                    $.hidePreloader();
                } else {
                    //启用用户操作
                    $.hidePreloader();
                    $.alert("错误代码:" + res.data.error + "," + res.data.mes);
                }
            },
            //响应失败
            function (res) {
                //启用用户操作
                $.hidePreloader();
                $.alert('请检查网络后重试');
            }
        )
    };

    $scope.showUserInfo2 = function () {
        //获取登录信息
        var token = app.getUserToken();

        if (!token) {
            return;
        }

        //操作等待禁用用户操作
        $.showPreloader('请稍候');
        //从服务器获取用户信息
        $http({
            method: 'get',
            url: net + '/user/isLogin',
            headers: {'Authorization': 'Bearer ' + token}
        }).then(
            //响应成功
            function (res) {
                if (!res.data.error) {

                    console.log(res.data);

                    //将获取的用户信息绑定给userInfo
                    $scope.userInfos = res.data.data;
                    console.log($scope.userInfos);
                    //因为userAvatar是只有图片文件名
                    //所以需要在前面加上服务器储存图片的地址，并自定义一个userAvatarAddress来储存
                    //地址：服务器路径+"/resources/img/"
                    $scope.userInfos.userAvatarAddress = net + "/resources/img/" + res.data.data.userAvatar;

                    //从服务器获得的性别数据不可以直接展示所以自定一个userSexWord来储存性别
                    //0:男，1:女
                    $scope.userInfos.userSexWord = $scope.userInfo.userSex == 0 ? "男" : "女";

                    //启用用户操作
                    $.hidePreloader();
                } else {
                    //启用用户操作
                    $.hidePreloader();
                    $.alert("错误代码:" + res.data.error + "," + res.data.mes);
                }
            },
            //响应失败
            function (res) {
                //启用用户操作
                $.hidePreloader();
                $.alert('请检查网络后重试');
            }
        )
    };
    $scope.logout = function () {
        localStorage.removeItem("ptsc_user_token");
        $.alert("您已注销成功", function () {
            location.reload();
        });
    };

    $scope.saveToMyGroup = function (status) {
        sessionStorage.setItem('ptsc_group_init_filter_status', status);
        app.turnHref('index.html', '#mine', 'my-group.html#my-all-group', true);
    }
});
/**
 * 搜索
 */
indexPage.controller('search', function ($scope, $http) {

    //声明选中类型
    $scope.typeChecked = {};
    $scope.typeChecked.goodsTypeId = null;
    $scope.typeChecked.goodsTypeName = '所有类型';

    //声明类型数组
    $scope.goodsTypes = [];

    $scope.keyWords = '';

    $scope.suiMobileInit = function (isNotChangeContent) {
        // alert(isNotChangeContent);
        app.suiInit(isNotChangeContent);
        var typeSaved = sessionStorage.getItem('ptsc_search_type_checked');
        var keyWords = sessionStorage.getItem('ptsc_search_key_words');
        if (typeSaved != null) {
            $scope.typeChecked = JSON.parse(typeSaved);
            sessionStorage.removeItem('ptsc_search_type_checked');
        }
        if (keyWords != null) {
            $scope.keyWords = keyWords;
            sessionStorage.removeItem('ptsc_search_key_words');
        }
    };

    //获取所有的团商品类型
    $scope.getAllGroupTypes = function () {
        $('body').removeClass('with-panel-right-cover');
        $http.get(net + '/group/find-all-type').then(function (res) {
            if (!res.error) {
                console.log(res.data);
                //将获取的所有商品类型绑定到类型列表
                $scope.goodsTypes = res.data.dataList;
                $scope.goodsTypes.unshift({goodsTypeName: '所有类型', goodsTypeId: null})

            }
            else
                $.alert("错误代码:" + res.data.error + "," + res.data.mes)
        }, function () {
            $.alert('网络或设置错误');
        })
    };

    $scope.$watch('typeChecked.goodsTypeId', function () {
        var name = $scope.typeChecked.goodsTypeName;
        if ($scope.goodsTypes.length == 0) {
            return;
        }
        for (var i = 0; i < $scope.goodsTypes.length; i++) {
            if ($scope.typeChecked.goodsTypeId == $scope.goodsTypes[i].goodsTypeId) {
                $scope.typeChecked.goodsTypeName = $scope.goodsTypes[i].goodsTypeName;
                break;
            }
        }
        if (i == $scope.goodsTypes.length) {
            $scope.typeChecked.goodsTypeName = '所有类型';
        }
        // console.log($scope.typeChecked);
        if (name != $scope.typeChecked.goodsTypeName) {
            $scope.getTheIndexGroup();
        }

    });

    // 自定义初始化请求数量
    var neededInfo = {line: 0, next: 5};

    // 获取搜索团信息
    $scope.getTheIndexGroup = function () {
        neededInfo = {line: 0, next: 5};
        //启用无限加载事件
        $.attachInfiniteScroll($('.infinite-scroll'));
        // 启用加载提示符
        $('.infinite-scroll-preloader').show();

        // 请求参数
        var params = neededInfo;
        params.keyWord = $scope.keyWords;
        params.goodsTypeId = $scope.typeChecked.goodsTypeId;

        $http({
            method: 'get',
            url: net + '/group/find-groups',
            params: params
        }).then(function (res) {
            console.log(res);
            $scope.allGroup = [];
            $scope.groupList = [];
            if (!res.data.error) {
                var groupList = res.data.dataList;
                for (var i = 0; i < groupList.length; i++) {
                    var singleImgs = [];
                    singleImgs = groupList[i];
                    singleImgs.src = eval(groupList[i].groupImgs);

                    for (var o = 0; o < singleImgs.src.length; o++) {
                        //遍历图片地址并加上服务器的url
                        singleImgs.src[o] = net + '/resources/img/' + singleImgs.src[o];
                    }
                    $scope.groupList.push(singleImgs);
                }
                if (groupList.length < neededInfo.next) {
                    // 加载完毕，则注销无限加载事件，以防不必要的加载
                    $.detachInfiniteScroll($('.infinite-scroll'));
                    // 删除加载提示符
                    $('.infinite-scroll-preloader').hide();
                }
                loading = false;
            } else {
                // $.alert("错误代码:" + res.data.error + "," + res.data.mes)
                // 加载完毕，则注销无限加载事件，以防不必要的加载
                $.detachInfiniteScroll($('.infinite-scroll'));
                // 删除加载提示符
                $('.infinite-scroll-preloader').hide();
                loading = false;
            }
        }, function () {
            $.alert('网络或设置错误');
        });

    };

    // 获取更多搜索团信息
    $scope.getMoreTheIndexGroup = function () {

        neededInfo.line = neededInfo.line + neededInfo.next;

        // 请求参数
        var params = neededInfo;
        params.keyWord = $scope.keyWords;
        params.goodsTypeId = $scope.typeChecked.goodsTypeId;

        $http({
            method: 'get',
            url: net + '/group/find-groups',
            params: params
        }).then(function (res) {
            console.log(res);
            if (!res.data.error) {
                var groupList = res.data.dataList;
                for (var i = 0; i < groupList.length; i++) {
                    var singleImgs = [];
                    singleImgs = groupList[i];
                    singleImgs.src = eval(groupList[i].groupImgs);

                    for (var o = 0; o < singleImgs.src.length; o++) {
                        //遍历图片地址并加上服务器的url
                        singleImgs.src[o] = net + '/resources/img/' + singleImgs.src[o];
                    }
                    $scope.groupList.push(singleImgs);
                }
                if (groupList.length < neededInfo.next) {
                    // 加载完毕，则注销无限加载事件，以防不必要的加载
                    $.detachInfiniteScroll($('.infinite-scroll'));
                    // 删除加载提示符
                    $('.infinite-scroll-preloader').hide();
                }
                loading = false;
            } else {
                // $.alert("错误代码:" + res.data.error + "," + res.data.mes)
                // 加载完毕，则注销无限加载事件，以防不必要的加载
                $.detachInfiniteScroll($('.infinite-scroll'));
                // 删除加载提示符
                $('.infinite-scroll-preloader').hide();
                loading = false;
            }
        }, function () {
            $.alert('网络或设置错误');
        });
    };

    $scope.$watch('keyWords', function () {
        $scope.getTheIndexGroup()
    });

    // 重置搜索条件
    $scope.reset = function () {
        $scope.keyWords = '';
        $scope.typeChecked.goodsTypeId = null;
    };

    //跳转团详情页面
    $scope.turnDetail = function (group) {
        sessionStorage.setItem('ptsc_detail_groupId', group.groupId);
        app.turnHref('index.html', '#search', 'group-detail.html');
    };

});

/**
 * 活动controller
 *
 */
indexPage.controller('active', function ($scope, $http) {
    $scope.activeList=[];
    $scope.lastpage = null;
    $scope.nowpage=null;
    $('.infinite-scroll-preloader').hide();
    $scope.activeList = [];
    $scope.getTheIndexActive = function () {
        $.showPreloader('请稍候');
        $http({
            method: 'get',
            url: net + '/activities/page/' + 1,
        }).then(function (res) {
            console.log(res);
            $.hidePreloader();
            if (!res.data.error) {
                $scope.allGroup = [];
                $scope.sliderSrcList = [];
                var groupList = res.data.data.list;
                $scope.lastpage = res.data.data.lastPage;
                $scope.lastpageis = res.data.data.hasNextPage;
                console.log($scope.lastpage);

                for (var i = 0; i < groupList.length; i++) {
                    var singleImgs = [];
                    if (groupList[i].activityImages) {
                        singleImgs = groupList[i].activityImages.replace("[", "").replace("]", "").replace(/\"/g, "").split(",");

                    }
                    for (var o = 0; o < singleImgs.length; o++) {
                        //遍历图片地址并加上服务器的url
                        singleImgs[o] = net + '/resources/img/' + singleImgs[o];
                    }
                    groupList[i].activityImages = singleImgs;

                }
                $scope.activeList = groupList;
                console.log($scope.activeList)
            } else {
                $.alert("错误代码:" + res.data.error + "," + res.data.mes)

            }
        }, function () {
            $.hidePreloader();
            $.alert('网络或设置错误');
        });
    };
    /**
     * 获得更多的团的信息
     * */
    $scope.getNextActive = function () {
        if ($scope.lastpageis ) {

            $.attachInfiniteScroll($('.infinite-scroll'));
            // 启用加载提示符
            $('.infinite-scroll-preloader').show();
            $http({
                method: 'get',
                url: net + '/activities/page/' + $scope.lastpage,
            }).then(function (res) {
                console.log(res.data);
                if (!res.data.error) {
                    var groupList = res.data.data.list;
                    if (groupList.length > 0) {
                        for (var i = 0; i < groupList.length; i++) {
                            var singleImgs = [];
                            if (groupList[i].activityImages) {
                                singleImgs = groupList[i].activityImages.replace("[", "").replace("]", "").replace(/\"/g, "").split(",");


                                for (var o = 0; o < singleImgs.length; o++) {
                                    //遍历图片地址并加上服务器的url
                                    singleImgs[o] = net + '/resources/img/' + singleImgs[o];
                                }
                                groupList[i].activityImages = singleImgs;
                                console.log(1);
                            }
                            $scope.activeList.push(groupList[i]);
                        }

                        console.log($scope.activeList);
                        $.detachInfiniteScroll($('.infinite-scroll'));
                        $('.infinite-scroll-preloader').hide();

                    } else {

                        $.alert("没有更多信息了");
                        $.detachInfiniteScroll($('.infinite-scroll'));
                        $('.infinite-scroll-preloader').hide();
                    }


                } else {
                    $.alert("错误代码:" + res.data.error + "," + res.data.mes);
                    // 加载完毕，则注销无限加载事件，以防不必要的加载

                    loading = false;
                }
            }, function () {
                $.alert('网络或设置错误');
            });
        }else{
            $.alert("没有更多信息了");
        }

    };

    $scope.turnactiveDetail = function (active) {
        sessionStorage.setItem('ptsc_detail_activeId', active.groupId);
        app.turnHref('index.html', '#index', 'activity-detail.html');
    };


});


/**
 * 咨询controller
 * **/
indexPage.controller('consult', function ($scope, $http) {


});

/**
 * 路由
 */
indexPage.config(function ($routeProvider) {
    $routeProvider.when('/mine', {
        templateUrl: 'html/mine-content.html',
        controller: 'mine'
    }).when('/index', {
        templateUrl: 'html/index-content.html',
        controller: 'index'
    }).when('/search', {
        templateUrl: 'html/search-content.html',
        controller: 'search'
    }).when('/active', {
        templateUrl: 'html/active-list-content.html',
        controller: 'active'
    }).when('/consult', {
        templateUrl: 'html/consult-list-content.html',
        controller: 'consult'
    }).otherwise({
        redirectTo: '/index'
    });
});